﻿/**************************************
 * 
 * author:李朴
 * company:上海沐雪网络科技有限公司
 * website:http://uweixin.cn
 * createDate:2013-11-1
 * update:2014-12-30
 * remark:支付成功后处理订单信息
 * 
 ***********************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Runtime.CompilerServices;
using MxWeiXinPF.BLL;
using MxWeiXinPF.Model;
using MxWeiXinPF.Web.weixin.jiaoshuifei;
using MxWeiXinPF.Common;
using MxWeiXinPF.WeiXinComm;

namespace MxWeiXinPF.Web.api.payment.wxpay
{
    /// <summary>
    /// 单例模式 处理订单
    /// </summary>
    public class wxOrderTmpMgr
    {
        static wxOrderTmpMgr uniCounter;
        private int totNum = 0;
        private wxOrderTmpMgr()
        {
            Thread.Sleep(400); //假设多线程的时候因某种原因阻塞400毫秒 
        }
        [MethodImpl(MethodImplOptions.Synchronized)] //方法的同步属性 
        static public wxOrderTmpMgr instance()
        {
            if (null == uniCounter)
            {
                uniCounter = new wxOrderTmpMgr();
            }
            return uniCounter;
        }


        /// <summary>
        /// 【微支付】 订单付款成功，处理订单：1将订单的状态改成付款完成；
        /// 李朴 add 
        /// </summary>
        /// <param name="beforeFunName"></param>
        /// <param name="out_trade_no">商户订单号</param>
        /// <param name="transaction_id">订单交易号</param>
        /// <param name="result_code">支付结果</param>
        /// <param name="total_fee">付款金额（单位为分）</param>
        /// <param name="otid">订单临时表id</param>
        /// <returns>有错误则返回错误信息，正确，则返回空字符串</returns>
        public string ProcessPaySuccess_wx(string beforeFunName, string out_trade_no, string transaction_id, string result_code, int total_fee, int otid, int wid)
        {

            string payTmpType = "【微支付】";
            decimal total_fee_d = (decimal)total_fee / 100;
            BLL.orders orderBll = new BLL.orders();

            string funName = payTmpType + beforeFunName + " ProcessPaySuccess_wx ";

           
            WXLogs.AddLog(wid, "微支付", funName, "开始执行ProcessPaySuccess_wx方法[otid:" + otid + "]");
            try
            {
              
                IList<Model.orders> orderlist = orderBll.GetModelList("id=" + otid + " and order_no='" + out_trade_no + "'");
                if (orderlist == null || orderlist.Count <= 0)
                {
                    WXLogs.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】订单号不存在", 0);
                    return "订单号不存在";
                }
                //这个暂时不处理
                if (WXLogs.ExistsFlg((out_trade_no + otid)))
                {  //如果已经处理过，则不再处理
                    return "";
                }
                WXLogs.AddFlg(wid, payTmpType, funName, (out_trade_no + otid));//加标志，防止重复提交

                Model.orders orderEntity = orderlist[0];
                if (orderEntity.order_amount > total_fee_d)
                {
                    return "付款的金额(" + total_fee_d + ")小于订单的预付款金额(" + orderEntity.order_amount + ")信息，直接退款";
                }
                orderEntity.notify_id = "";
                orderEntity.trade_no = transaction_id;
                orderEntity.pay_info = result_code;
                orderEntity.order_amount = total_fee_d;
                orderEntity.payment_time = DateTime.Now;
                orderEntity.status = 2;
                orderEntity.payment_status = 2;

                //判断是否需要立即发货
                if (orderEntity.express_status == 0)
                {
                    //立即发货

                    orderEntity.express_status = 2;
                    orderEntity.express_time = DateTime.Now;


                    //FaHuoProc fahuo = new FaHuoProc();
                    
                    //BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay();
                    //Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid);
                    //Dictionary<string, object> fahuoDict = fahuo.fahuomgr(paymentInfo, orderEntity);
                    //string errcode = fahuoDict["errcode"].ToString();
                    //string errmsg = fahuoDict["errmsg"].ToString();
                    //orderEntity.fahuoCode = errcode;
                    //orderEntity.fahuoMsg = errmsg;
                    //if (errcode == "0")
                    //{
                    //    orderEntity.express_status = 2;
                    //    orderEntity.express_time = DateTime.Now;
                    //}
                    //else
                    //{
                    //    orderEntity.express_status =1;
                    //}
                }

                bool ret = orderBll.Update(orderEntity);
                //把订单里的商品库存减少

                #region 处理具体的模块数据
                if (orderEntity.modelCode == orderModelCodeEnum.shop.ToString())
                {
                    procShopOrder(orderEntity);
                }
                else if (orderEntity.modelCode == orderModelCodeEnum.jiaoshuifei.ToString())
                {
                     
                    WXLogs.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】交水费业务Begin", 0);
                    procJiaoShuiFei(orderEntity, wid);
                }

                    #endregion


                    if (!ret)
                {
                    WXLogs.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据失败", 0);
                    return "订单号【" + out_trade_no + "】支付成功后处理数据失败";
                }

                WXLogs.AddLog(payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后，处理数据成功", 1);
                return "";

               

            }
            catch (Exception ex)
            {

                WXLogs.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据同步出现错误：" + ex.Message, 0);
                return null;
            }

        }

        /// <summary>
        /// 微商城订单处理---减少库存
        /// </summary>
        /// <param name="orderEntity"></param>
        /// <returns></returns>
        private bool procShopOrder(Model.orders orderEntity)
        {
            bool ret = true;

            BLL.wx_shop_product spBll = new BLL.wx_shop_product();
            BLL.orders oBll = new BLL.orders();
            //根据订单号得到订单
            Model.orders oModel = oBll.GetModelByNo(orderEntity.order_no);
            //得到所有订购商品
            List<Model.order_goods> ogList = oModel.order_goods;
            //根据订购商品的数量修改库存
            foreach (Model.order_goods item in ogList)
            {
                Model.wx_shop_product spModel = spBll.GetModel(item.goods_id);
                spModel.stock = spModel.stock - item.quantity;
                ret=spBll.Update(spModel);

            }
            return ret;
        }



        /// <summary>
        ///处理缴水费的订单
        ///2017-4-11 添加退款功能
        /// </summary>
        /// <param name="orderEntity"></param>
        /// <returns></returns>
        private bool procJiaoShuiFei(Model.orders orderEntity,int wid)
        {
            string logModuleName = "微支付-处理缴水费的订单";
            WXLogs.AddLog(wid, logModuleName, "procJiaoShuiFei", "回调开始order_no=" + orderEntity.order_no);

            string msg = string.Empty;
            string api_rtncode = string.Empty;
            try
            {
                BLL.shuifei_payment_record recordBLL = new BLL.shuifei_payment_record();
                Model.shuifei_payment_record recordModel = recordBLL.GetModelByWidAndOrderId(wid, orderEntity.order_no);
                if (recordModel == null)
                {
                    return false;
                }
                string key = "";
                string apiurl = "";
                string wxusername = "";
                MxWeiXinPF.BLL.shuifei_baseinfo _baseInfoBLL = new BLL.shuifei_baseinfo();
                Model.shuifei_baseinfo baseinfoModel = _baseInfoBLL.GetModelByWid(wid);
                if (baseinfoModel != null)
                {
                    key = baseinfoModel.api_Key;
                    apiurl = baseinfoModel.api_url;
                    wxusername = baseinfoModel.api_UserName;

                }
                jsf_bindOne paydo = new jsf_bindOne();
                WXLogs.AddLog(wid, logModuleName, "procJiaoShuiFei", "回调开始-调第3方接口");
                bool ret = paydo.PayDo(orderEntity.order_no, Convert.ToInt32(orderEntity.order_amount * 100), recordModel.consno, orderEntity.openid, wxusername, key, apiurl, "", out msg, out api_rtncode);
                recordModel.pay_status = 1;
                recordModel.pay_success_time = DateTime.Now;
                if (ret)
                {

                    WXLogs.AddLog(wid, logModuleName, "procJiaoShuiFei", "procJiaoShuiFei=>paydo.PayDo=>SUCCESSorder_no=" + orderEntity.order_no);
                }
                else
                {
                    //接口调用失败，则退款。
                    WXPayHelper wxpay = new WXPayHelper();
                   Dictionary<string ,string> refDit=  wxpay.Refund(orderEntity,(int)(orderEntity.order_amount * 100));
                    if (refDit != null && !string.IsNullOrEmpty(refDit["msg"]))
                    {
                        recordModel.remark = refDit["msg"];
                    }

                    WXLogs.AddErrLog(wid, logModuleName, "procJiaoShuiFei", "procJiaoShuiFei=>paydo.PayDo=>FAIL,order_no=" + orderEntity.order_no+"msg：" + msg);
                    recordModel.remark = "procJiaoShuiFei=>paydo.PayDo=>FAIL,msg：" + msg;
                }
                recordModel.api_rtnmsg = msg;
                recordModel.api_rtncode = api_rtncode;
                recordBLL.Update(recordModel);

                return ret;
            }
            catch (Exception ex)
            {
                WXLogs.AddErrLog(wid, logModuleName, "procJiaoShuiFei", "procJiaoShuiFei执行,order_no=" + orderEntity.order_no+"Error：" + ex.Message);
                return false;
            }
            finally
            {
                WXLogs.AddLog(wid, logModuleName, "procJiaoShuiFei", "回调结束order_no=" + orderEntity.order_no);
            }
        }

        public void Inc() { totNum++; }
        public int GetCounter() { return totNum; }
    }
}